package com.rosense.client.rpc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.rmi.Naming;

import com.rosense.server.Version;

/**
 * 
 * rmi://localhost:8088/rpc
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年1月23日 下午3:17:28
 *
 */
public class RPCClientProcess {
	private String ip;
	private String port;

	public RPCClientProcess(String ip, String port) {
		this.ip = ip;
		this.port = port;
	}

	public void send(RPCBean rpcBean) {
		try {
			IRPCServer<RPCBean> server = (IRPCServer<RPCBean>) Naming.lookup("rmi://" + ip + ":" + port + "/rpc");
			RPCBean bean = server.get();
			if (bean != null) {
				/*当版本发送变化时，更新jar包*/
				if (bean.version > Version.version) {
					RpcJarBean jarBean = server.getJar();
					if (jarBean != null) {
						FileOutputStream fos = null;
						File file = new File("linux-monitor.jar");
						try {
							fos = new FileOutputStream(file);
							fos.write(jarBean.bytes);
							fos.flush();
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							try {
								fos.close();
								restart();
							} catch (IOException e) {
							}
						}
					}
				}
			}
			server.set(rpcBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void restart() {
		Process pro1;
		Runtime r = Runtime.getRuntime();
		try {
			String command = "nohup ./startup.sh &";
			//第一次采集流量数据  
			pro1 = r.exec(command);
			pro1.destroy();
		} catch (IOException e) {
		} finally {
			System.exit(-1);
		}
	}
}
